package net.asfun.jvalog.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.Query;

import net.asfun.jvalog.misc.Formater;
import net.asfun.jvalog.po.Phase;
import net.asfun.jvalog.service.Jdoer;
import net.asfun.jvalog.service.JdoerFactory;
import net.asfun.jvalog.view.SiteInfo;

public class Archive {

	private Phase phase;
	
	private Archive(Phase pha) {
		phase = pha;
	}
	
	public Date getDate() {
		return phase.getDate();
	}
	
	public int getCount() {
		return phase.getCount();
	}
	
	public String getLink() {
		return SiteInfo.getInstance().getUrl() + Formater.date2string(phase.getDate(), "yyyy/MM");
	}
	
	protected static Phase getStage(Date date) {
		Jdoer<Phase> jdp = JdoerFactory.getPhaseJdo();
		String ym = Formater.date2string(date, "yyyyMM");
		Phase pha = jdp.unique("yearMonth == '" + ym + "'");
		if ( pha == null ) {
			pha = new Phase();
			pha.setYearMonth(ym);
			pha.setDate(date);
			jdp.save(pha);
		}
		return pha;
	}
	
	public static List<Archive> listAll(int size) {
		ArrayList<Archive> res = new ArrayList<Archive>();
		Jdoer<Phase> jdp = JdoerFactory.getPhaseJdo();
		Query q = jdp.prepareQuery();
//		q.setFilter("count > 0"); TODO use count in query
		q.setOrdering("date descending");
		q.setRange(0, size);
		Collection<Phase> clt = jdp.more(q);
		for(Phase pha : clt) {
			res.add(new Archive(pha));
		}
		return res;
	}
	
}
